<template>
  <Modal
    v-model="showForm"
    :title="isEdit ? '编辑' : '新增'"
    :draggable="true"
    :mask-closable="false"
    @on-cancel="handleCancel"
    footer-hide
  >
    <Form
      :model="formItem"
      :label-width="80"
      ref="formItem"
      :rules="createRules"
    >
      <FormItem label="名称" prop="department_name">
        <Input v-model="formItem.department_name" placeholder="请输入名称" />
      </FormItem>
      <FormItem label="父级" prop="pid">
        <TreeSelect
          v-model="formItem.pid"
          :data="departmentList"
          placeholder="请选择父级"
          @on-change="changePid"
        />
      </FormItem>
      <FormItem label="排序" prop="sort">
        <Input
          v-width="100"
          v-model.trim="formItem.sort"
          placeholder=""
          type="number"
        />
      </FormItem>
      <FormItem label="部门类型" prop="department_type">
        <Select v-model="formItem.department_type" placeholder="请选择部门类型">
          <Option
            :value="+index"
            v-for="(item, index) in typeList"
            :key="item"
            >{{ item }}</Option
          >
        </Select>
      </FormItem>
      <FormItem label="职能" prop="competency_ids">
        <Select
          v-model="formItem.competency_ids"
          placeholder="请选择职能"
          multiple
        >
          <Option
            :value="+item.value"
            v-for="item in competencyList"
            :key="item.value"
            >{{ item.label }}</Option
          >
        </Select>
      </FormItem>
      <FormItem label="角色" prop="role_ids">
        <Select
          multiple
          filterable
          v-model="formItem.role_ids"
          placeholder="请选择角色"
          @on-change="changeRole"
        >
          <Option
            :value="+item.value"
            v-for="item in roleList"
            :key="item.value"
            >{{ item.label }}</Option
          >
        </Select>
      </FormItem>
      <FormItem label="默认角色" prop="default_role_ids">
        <Select
          multiple
          filterable
          v-model="formItem.default_role_ids"
          placeholder="请选择默认角色"
        >
          <Option
            :value="+item.value"
            v-for="item in defaultRoleList"
            :key="item.value"
            >{{ item.label }}</Option
          >
        </Select>
      </FormItem>
      <FormItem label="状态" prop="status">
        <i-switch v-model="formItem.status">
          <span slot="open">On</span>
          <span slot="close">Off</span>
        </i-switch>
      </FormItem>
    </Form>

    <div class="modalFoot">
      <Button @click="handleCancel()">取消</Button>
      <Button
        class="ivu-ml-16"
        :loading="btnLoading"
        type="primary"
        @click="handleSave()"
        >确定</Button
      >
    </div>
  </Modal>
</template>
<script>
import {
  getDeptEditInfo,
  addDepartment,
  editDepartment,
} from "@/api/TApi/index.js";
export default {
  data() {
    return {
      showForm: false,
      isEdit: false,
      btnLoading: false,
      currentId: 0,
      defaultRoleList: [],
      competencyList: [],
      departmentList: [],
      roleList: [],
      typeList: [],
      btnLoading: false,
      formItem: {
        department_name: "",
        pid: 0,
        sort: null,
        department_type: "",
        competency_ids: [],
        role_ids: [],
        default_role_ids: [],
        status: true,
      },
      createRules: {
        department_name: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        department_type: [
          {
            required: true,
            message: "请选择部门类型",
            type: "number",
            trigger: "change",
          },
        ],
        competency_ids: [
          {
            required: true,
            type: "array",
            message: "请选择职能",
            trigger: "change",
          },
        ],
        role_ids: [
          {
            required: true,
            type: "array",
            message: "请选择角色",
            trigger: "change",
          },
        ],
        default_role_ids: [
          {
            required: true,
            type: "array",
            message: "请选择默认角色",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    initData() {
      this.formItem = {
        department_name: "",
        pid: 0,
        sort: null,
        department_type: "",
        competency_ids: [],
        role_ids: [],
        default_role_ids: [],
        status: true,
      };
      this.currentId = 0;
      this.defaultRoleList = [];
      this.competencyList = [];
      this.departmentList = [];
      this.roleList = [];
      this.typeList = [];
      this.$refs.formItem.resetFields();
    },
    getEditInfo(id, pid, type = "") {
      if (type !== "change") {
        this.initData();
      }
      this.isEdit = id ? true : false;
      this.currentId = id;
      this.showForm = true;
      getDeptEditInfo({ id, pid }).then((res) => {
        this.competencyList = res.condition.competency;
        this.roleList = res.condition.role;
        if (type != "change") {
          this.departmentList = this.changeData(res.condition.department);
          this.typeList = res.condition.type;
          this.formItem = {
            department_name: res.department_name,
            pid: res.pid,
            sort: res.sort,
            department_type: +res.department_type,
            competency_ids: res.competency_ids,
            role_ids: res.role_ids,
            default_role_ids: res.default_role_ids,
            status: res.status == 1 ? true : false,
          };
        } else {
          this.formItem.competency_ids = res.competency_ids;
          this.formItem.role_ids = res.role_ids;
          this.formItem.default_role_ids = res.default_role_ids;
        }
      });
    },
    changeData(data) {
      data.forEach((item) => {
        item.title = item.label;
        item.expand = true;
        item.selected = false;
        if (item.children && item.children.length > 0) {
          this.changeData(item.children);
        }
      });
      return data;
    },
    changePid(e) {
      if (e !== undefined) {
        let pid = e ? e : 0;
        this.getEditInfo(this.currentId, pid, "change");
      }
    },
    changeRole(e) {
      this.defaultRoleList = this.roleList.filter((item) => {
        return e.includes(+item.value);
      });

      this.changeDefaultRole();
    },
    changeDefaultRole() {
      let allRoleIds = [];
      allRoleIds = this.defaultRoleList.map((item) => {
        return +item.value;
      });
      this.formItem.default_role_ids.forEach((item, index) => {
        if (!allRoleIds.includes(+item)) {
          this.formItem.default_role_ids.splice(index, 1);
        }
      });
    },
    handleSave() {
      this.$refs["formItem"].validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          let params = {
            department_name: this.formItem.department_name,
            pid: this.formItem.pid,
            sort: this.formItem.sort,
            department_type: this.formItem.department_type,
            competency_ids: this.formItem.competency_ids,
            role_ids: this.formItem.role_ids,
            default_role_ids: this.formItem.default_role_ids,
            status: this.formItem.status ? 1 : 0,
          };
          if (this.isEdit) {
            params.id = this.currentId;
            editDepartment(params)
              .then((res) => {
                this.$Message.success("保存成功！");
                this.btnLoading = false;
                this.showForm = false;
                this.$emit("refresh");
              })
              .catch(() => {
                this.btnLoading = false;
              });
          } else {
            addDepartment(params)
              .then((res) => {
                this.$Message.success("保存成功！");
                this.btnLoading = false;
                this.showForm = false;
                this.$emit("refresh");
              })
              .catch(() => {
                this.btnLoading = false;
              });
          }
        }
      });
    },
    handleCancel() {
      this.showForm = false;
    },
  },
};
</script>
<style lang="less" scoped>
.modalFoot {
  text-align: right;
  border-top: 1px solid #ddd;
  padding-top: 16px;
  margin-top: 24px;
}
</style>
